﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		PageRepository.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 //   File:            PageRepository.cs
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System;
using System.Collections.Generic;
using System.Linq;
using Dexter.Core.Data.Repository;
using Dexter.Domain.Model;
using Dexter.Domain.Results;
using Dexter.Logger.Contracts;
using Dexter.Repository.NHibernate.Queries;
using NHibernate;
using Topics.Radical.Validation;
using ISessionFactory = Dexter.Repository.NHibernate.SessionFactory.ISessionFactory;

namespace Dexter.Repository.NHibernate.Repositories {
	/// <summary>
	/// The implementation of <see cref="IPageRepository"/>.
	/// </summary>
	/// <example>The following is an example of initializing 
	///          an <c>PageRepository</c> type:
	///   <code>
	///       // Create the type.
	///       PageRepository ds = new PageRepository;
	/// 
	///       if ( null == ds )
	///           return;
	/// 
	///       return ds.DoSomething( 5 );
	///   </code>
	/// </example>
	public class PageRepository : RepositoryBase <Page> , IPageRepository {

		/// <summary>
		/// Initializes a new instance of the <see cref="PageRepository"/> class.
		/// </summary>
		/// <param name="sessionFactory">The session factory.</param>
		/// <param name="logger">The logger.</param>
		public PageRepository ( ISessionFactory sessionFactory , ILogger logger ) : base ( sessionFactory , logger ) {}

		#region Implementation of IPageRepository

		/// <summary>
		/// Retrieve a page from a specific slug.
		/// </summary>
		/// <param name="slug">The slug of the page.</param>
		/// <returns>
		/// An instance of Page.
		/// The return item could be null if there isn't an item with the specified slug into the repository.
		/// </returns>
		/// <exception cref="ArgumentNullException"> If <paramref name="slug"/> is <c>null</c> or <c>empty</c>.</exception>
		public virtual Page GetBySlug ( string slug ) {
			return GetBySlug ( slug , true );
		}

		/// <summary>
		/// Retrieve a page from a specific slug.
		/// </summary>
		/// <param name="slug">The slug of the page.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An instance of Page.
		/// The return item could be null if there isn't an item with the specified slug into the repository.
		/// </returns>
		/// <exception cref="ArgumentNullException"> If <paramref name="slug"/> is <c>null</c> or <c>empty</c>.</exception>
		public virtual Page GetBySlug ( string slug, bool enableTracking ) {
			Ensure.That ( slug )
				.Named ( "slug" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNullNorEmpty ( )
				.WithMessage ( "Invalid page slug." );

			var returnItem = Session.GetNamedQuery ( KnownQueries.PageRepository.GetBySlug )
				.SetReadOnly ( !enableTracking )
				.SetParameter ( "slug" , slug )
				.UniqueResult <Page> ( );

			return returnItem;
		}

		/// <summary>
		/// Retrieve a page from a specific slug.
		/// </summary>
		/// <param name="slug">The slug of the page.</param>
		/// <returns>
		/// An instance of Page with its complete tree loaded.
		/// The return item could be null if there isn't an item with the specified slug into the repository.
		/// </returns>
		/// <exception cref="ArgumentNullException"> If <paramref name="slug"/> is <c>null</c> or <c>empty</c>.</exception>
		public virtual Page GetBySlugWithParent ( string slug ) {
			return GetBySlugWithParent ( slug , true );
		}

		/// <summary>
		/// Retrieve a page from a specific slug.
		/// </summary>
		/// <param name="slug">The slug of the page.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An instance of Page with its complete tree loaded.
		/// The return item could be null if there isn't an item with the specified slug into the repository.
		/// </returns>
		/// <exception cref="ArgumentNullException"> If <paramref name="slug"/> is <c>null</c> or <c>empty</c>.</exception>
		public virtual Page GetBySlugWithParent ( string slug, bool enableTracking ) {
			Ensure.That ( slug )
				.Named ( "slug" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNullNorEmpty ( )
				.WithMessage ( "Invalid page slug." );

			var returnItem = Session.GetNamedQuery ( KnownQueries.PageRepository.GetBySlugWithParent )
				.SetReadOnly ( !enableTracking )
				.SetParameter ( "slug" , slug )
				.UniqueResult <Page> ( );

			return returnItem;
		}

		/// <summary>
		/// Retrieve a page from a specific key.
		/// </summary>
		/// <param name="key">The key.</param>
		/// <returns>
		/// An instance of Page.
		/// The return item could be null if there isn't an item with the specified key into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="key"/> is lesser then 1.</exception>
		public virtual Page GetByKey ( int key ) {
			return GetByKey ( key , true );
		}

		/// <summary>
		/// Retrieve a page from a specific key.
		/// </summary>
		/// <param name="key">The key.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An instance of Page.
		/// The return item could be null if there isn't an item with the specified key into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="key"/> is lesser then 1.</exception>
		public virtual Page GetByKey ( int key, bool enableTracking ) {
			Ensure.That ( key )
				.Named ( "key" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page key" );

			var returnItem = Session.GetNamedQuery ( KnownQueries.PageRepository.GetByKey )
				.SetReadOnly ( !enableTracking )
				.SetParameter ( "key" , key )
				.UniqueResult <Page> ( );

			return returnItem;
		}

		/// <summary>
		/// Retrieve a page from a specific key.
		/// </summary>
		/// <param name="key">The key.</param>
		/// <returns>
		/// An instance of Page with its complete tree loaded.
		/// The return item could be null if there isn't an item with the specified key into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="key"/> is lesser then 1.</exception>
		public virtual Page GetByKeyWithParent ( int key ) {
			return GetByKeyWithParent ( key , true );
		}

		/// <summary>
		/// Retrieve a page from a specific key.
		/// </summary>
		/// <param name="key">The key.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An instance of Page with its complete tree loaded.
		/// The return item could be null if there isn't an item with the specified key into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="key"/> is lesser then 1.</exception>
		public virtual Page GetByKeyWithParent ( int key, bool enableTracking ) {
			Ensure.That ( key )
				.Named ( "key" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page key" );

			var returnItem = Session.GetNamedQuery ( KnownQueries.PageRepository.GetByKeyWithParent )
				.SetReadOnly ( !enableTracking )
				.SetParameter ( "key" , key )
				.UniqueResult <Page> ( );

			return returnItem;
		}

		///<summary>
		///	Retireve a paged list of all <see cref="Page"/>.
		///</summary>
		/// <remarks>
		///		The result will include published only pages.
		///		Moreover the result hasn't the tracking system enabled
		/// </remarks>
		///<param name = "pageIndex">Index of the page (0 based).</param>
		///<param name = "pageSize">The number of items to retrieve.</param>
		/// <param name = "enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		///<returns>An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.</returns>
		public virtual IPagedResult<Page> GetPages ( int pageIndex, int pageSize, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsGreaterThen ( 0, Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			IFutureValue<long> total = Session.GetNamedQuery ( KnownQueries.PageRepository.GetPagedListCount )
							.SetFirstResult ( pageIndex * pageSize )
							.FutureValue<long> ( );

			IEnumerable<Page> result = Session.GetNamedQuery ( KnownQueries.PageRepository.GetPagedList )
				.SetFirstResult ( pageIndex * pageSize )
				.SetMaxResults ( pageSize )
				.SetReadOnly ( !enableTracking )
				.Future<Page> ( );

			return new PagedResult<Page> ( pageIndex, pageSize, result.ToList ( ), total.Value );
		}


		/// <summary>
		/// Retrieve the complete pages structure roots with all childs and parent loaded.
		/// This might me used to generate a pages menu
		/// </summary>
		/// <returns>
		/// A set of instances of PageStructure with its complete tree loaded.
		/// The return item could be null if there aren't pages into the repository.
		/// </returns>
		public virtual IEnumerable<PageStructure> GetPagesStructureRoot()
		{
			return GetPagesStructureRoot(false);
		}

		/// <summary>
		/// Retrieve the complete pages structure roots with all childs and parent loaded
		/// This might me used to generate a pages menu
		/// </summary>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// A set of instances of PageStructure with its complete tree loaded.
		/// The return item could be null if there aren't pages into the repository.
		/// </returns>
		public virtual IEnumerable<PageStructure> GetPagesStructureRoot(bool enableTracking)
		{
			PageStructure[] result = Session.GetNamedQuery(KnownQueries.PageRepository.GetPagesStructureRootList)
				.SetReadOnly(!enableTracking)
				.List<PageStructure>()
				.ToArray();

			return result;
		}

		/// <summary>
		/// Retrieve the complete pages structure with all childs and parent loaded
		/// </summary>
		/// <returns>
		/// A set of  instances of PageStructure with its complete tree loaded.
		/// The return item could be null if there aren't pages into the repository.
		/// </returns>
		public virtual IEnumerable<PageStructure> GetPagesStructure ( ) {
			return GetPagesStructure ( true );
		}

		/// <summary>
		/// Retrieve the complete pages structure with all childs and parent loaded
		/// </summary>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// A set of  instances of PageStructure with its complete tree loaded.
		/// The return item could be null if there aren't pages into the repository.
		/// </returns>
		public virtual IEnumerable<PageStructure> GetPagesStructure ( bool enableTracking ) {
			PageStructure[] result = Session.GetNamedQuery ( KnownQueries.PageRepository.GetPagesStructureList )
				.SetReadOnly ( !enableTracking )
				.List <PageStructure> ( )
				.ToArray ( );

			return result;
		}

		/// <summary>
		/// Retrieve a paged list of pages structure with all childs and parent loaded
		/// </summary>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<PageStructure> GetPagesStructureList ( int pageSize, int pageIndex ) {
			return GetPagesStructureList ( pageIndex , pageSize , true );
		}

		/// <summary>
		/// Retrieve a paged list of pages structure with all childs and parent loaded
		/// </summary>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<PageStructure> GetPagesStructureList ( int pageSize, int pageIndex, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 , Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			IFutureValue <long> total = Session.GetNamedQuery ( KnownQueries.PageRepository.GetPagesStructureListCount )
				.FutureValue <long> ( );

			IEnumerable <PageStructure> result = Session.GetNamedQuery ( KnownQueries.PageRepository.GetPagesStructureList )
				.SetFirstResult ( pageIndex * pageSize )
				.SetMaxResults ( pageSize )
				.SetReadOnly ( !enableTracking )
				.Future <PageStructure> ( );

			return new PagedResult<PageStructure>(pageIndex, pageSize, result.ToList(), total.Value);
		}

		/// <summary>
		/// Retrieve all used slugs from the Pages.
		/// </summary>
		/// <returns>An array of slugs.</returns>
		/// A set of  strings.
		/// The return item could be null if there aren't pages into the repository.
		public virtual IList<string> GetAllPagesSlugs()
		{
			return Session.GetNamedQuery ( KnownQueries.PageRepository.GetAllPagesSlugs )
				.List <string> ( )
				.ToList( );
		}

		/// <summary>
		/// This method remove a page and all childs from the repository.
		/// </summary>
		/// <param name="item">The item to delete.</param>
		/// <exception cref="ArgumentNullException"> If <paramref name="item"/> is <c>null</c>.</exception>
		public virtual void Delete ( Page item ) {
			Ensure.That ( item )
				.Named ( "item" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNull ( )
				.WithMessage ( "Invalid page." );

			item.ValidateForDelete ( );

			Session.Delete ( item );
		}

		/// <summary>
		/// Saves the specified page.
		/// </summary>
		/// <param name="item">The item to save.</param>
		/// <exception cref="ArgumentNullException"> If <paramref name="item"/> is <c>null</c>.</exception>
		public virtual void Save ( Page item ) {
			Ensure.That ( item )
				.Named ( "item" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNull ( )
				.WithMessage ( "Invalid page." );

			item.ValidateForSave ( );

			Session.SaveOrUpdate ( item );
		}

		/// <summary>
		/// Updates the specified page.
		/// </summary>
		/// <param name="item">The item to update.</param>
		/// <exception cref="ArgumentNullException"> If <paramref name="item"/> is <c>null</c>.</exception>
		public virtual void Update ( Page item ) {
			Ensure.That ( item )
				.Named ( "item" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNull ( )
				.WithMessage ( "Invalid page." );

			item.ValidateForUpdate ( );

			Session.SaveOrUpdate ( item );
		}

		#endregion
	}
}
